import React, { Component } from 'react'
import { Descriptions, Button, Avatar, List, Pagination, Image, Modal, message, Input } from 'antd';
import { connect } from 'react-redux'
import { history } from '@/index'
import { selectedOrderData } from '@/Redux/ActionTypes/public/BaseTable/publicActionCreator'
import './index.css'
import { refundThunk, managerBorderOfficialCancelThunk } from './ActionCreators'

const orderStatus = { 0: '未支付', 1: '已取消', 2: '已支付', 3: '已发货', 4: '已完成', 5: '退货中', 6: '已退货', 7: '已退款' }
const expressStatus = { 0: '未寄件', 1: '未揽件', 2: '已揽件', 3: '已收货' }

const mapStateToProps = (state) => ({
})

const mapDispatchToProps = (dispatch) => ({
  setSelectedOrderData: (...rest) => dispatch(selectedOrderData(...rest)),
  refund: (...rest) => dispatch(refundThunk(...rest)), // 退款
  managerBorderOfficialCancel: (...rest) => dispatch(managerBorderOfficialCancelThunk(...rest)), // 取消揽件
})
@connect(mapStateToProps, mapDispatchToProps)
class Order extends Component {

  state = {
    loading: true,
    canCancleExpress: false, // 是否可以取消揽件
    canReturnMoney: false, // 是否可以退款
    isModalVisible: false, // 退款模态框是否显示
    isModalVisible2: false
  }

  componentDidMount() {
    const { totalPage } = this.props
  }

  returnOrderConfig = () => {
    const { orderConfig, orderData } = this.props
    let orderList = []
    orderData?.forEach(element1 => {
      let ele1 = element1
      let order = {}
      // 循环匹配订单每一项
      ele1.bookList.forEach(bookItem => {
        orderConfig.forEach(configItem => {
          if (bookItem[Object.keys(configItem)[0]]) {
            order[Object.values(configItem)[0]] = bookItem[Object.keys(configItem)[0]]
          } else {
            order[Object.values(configItem)[0]] = ele1[Object.keys(configItem)[0]]
          }
        })
        Object.assign(order, {
          url: bookItem.url,
          total: ele1.total,
          orderId: ele1.orderId,
          orderStatus: String(ele1.orderStatus),
          address: ele1.addressVo.address,
          receiveName: ele1.addressVo.receiveName,
          expressStatus: ele1.expressStatus,
          freight: ele1.freight,
          '下单人': ele1.addressVo.receiveName
        })

        switch (order.orderStatus) {
          case '0':
            order.className = "status-color-red"
            break;
          case '1':
            order.className = "status-color-blue"
            break;
          case '2':
            order.className = "status-color-green"
            break;
          case '3':
            order.className = "status-color-green"
            break;
          case '4':
            order.className = "status-color-green"
            break;
          case '5':
            order.className = "status-color-blue"
            break;
          case '6':
            order.className = "status-color-red"
            break;
          case '7':
            order.className = "status-color-blue"
            break;
          default:
            break;
        }
      })
      order.bookList = ele1.bookList
      orderConfig.forEach(configItem => {
        if (ele1.addressVo[Object.keys(configItem)[0]]) {
          order[Object.values(configItem)[0]] = ele1.addressVo[Object.keys(configItem)[0]]
        }
      })

      orderList.push(order)


    })
    return orderList
  }

  seeOrderMessage = (orderMessage) => {
    const { setSelectedOrderData } = this.props
    setSelectedOrderData(orderMessage)
    history.push('/homePage/mallManagement/orderManagement/orderMessage')
  }

  handleOk = () => {
    const { refund, selectedOrderData } = this.props
    refund(selectedOrderData['单号'], this.refs.txt.resizableTextArea.props.value).then(res => {
      if (res.success) {
        message.success('退款成功')
      }
    })
    this.setState({
      isModalVisible: false
    })
  }

  handleOk2 = () => {
    const { selectedOrderData, managerBorderOfficialCancel } = this.props
    managerBorderOfficialCancel('计划有变，暂时不寄了', selectedOrderData.orderId).then(res => {
      if (res.data.success) {
        message.success(res.data.data)
      } else {
        message.error(res.data.data)
      }
    })

    this.setState({
      isModalVisible2: false
    })
  }

  handleCancel = () => {
    this.setState({
      isModalVisible: false
    })
  }

  handleCancel2 = () => {
    this.setState({
      isModalVisible2: false
    })
  }

  componentDidUpdate() {

  }

  render() {
    const orderList = this.returnOrderConfig()
    const { changePage, statusValue, totalCount } = this.props
    const { selectedOrderData, isOrderMessage, orderConfig } = this.props
    // 判断是否是查看某个订单的详情
    return (
      <div className="order-message">
        {
          (isOrderMessage || selectedOrderData?.isOrderMessage) &&
          <div style={{
            position: 'relative',
            paddingLeft: "200px"
          }}>
            <Image
              width={120}
              style={{
                position: 'absolute',
                left: '-150px',
                top: '50px'
              }}
              src={selectedOrderData.url}
            />
            <Descriptions
              title={<div className="order-title">{`单号：${selectedOrderData['单号']}`}</div>}
              column={2}
              size={'small'}
              style={{
                width: '800px'
              }}
              labelStyle={{
                width: '100px',
                textAlign: 'center',
              }}
            >
              <Descriptions.Item label="下单人">{selectedOrderData.receiveName}</Descriptions.Item>
              <Descriptions.Item label="下单时间">{selectedOrderData['下单时间']}</Descriptions.Item>
              <Descriptions.Item label="收货地址">{selectedOrderData.address}</Descriptions.Item>
            </Descriptions>
            <div className="status-amount">
              <div className="order-status">
                物流状态
              <div className={`status0`} style={{ fontSize: "17px" }}>{expressStatus[selectedOrderData.expressStatus]}</div>
              </div>
              <div className="order-status">
                订单状态
              <div className={`status0 ${selectedOrderData.className}`} style={{ fontSize: "17px" }}>{orderStatus[selectedOrderData.orderStatus]}</div>
              </div>
              <div className="order-amount">
                订单金额
                <div className="amount" style={{ fontSize: "17px" }}>
                  {"￥ " + selectedOrderData.total}
                </div>
              </div>
            </div>
            <div className="mall-order-button">
              <Button
                type={'primary'}
                key={Math.random()}
                disabled={(selectedOrderData.expressStatus === 1 && selectedOrderData.orderStatus === '2') ? false : true}
                onClick={() => {
                  this.setState({
                    isModalVisible2: true
                  })
                }}
              >取消揽件</Button>
              <Button type={'primary'}
                style={{ marginLeft: '20px' }}
                onClick={() => {
                  this.setState({
                    isModalVisible: true
                  })
                }}
              >退款</Button>
            </div>
            <Modal title="提示" visible={this.state.isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel} centered={true}>
              <Input.TextArea allowClear rows={4} placeholder="请输入退款原因" maxLength={6} ref="txt" />
            </Modal>
            <Modal title="提示" visible={this.state.isModalVisible2} onOk={this.handleOk2} onCancel={this.handleCancel2} centered={true}>
              <p>订单ID：{selectedOrderData.orderId}</p>
              <p>是否确定取消揽件？</p>
            </Modal>

          </div>
        }
        {
          !isOrderMessage && <List
            itemLayout="horizontal"
            dataSource={orderList}
            pagination={{
              onChange: (page, size) => {
                // 判断选择的订单状态
                switch (statusValue) {
                  case '1':
                    changePage({ page, size })
                    break;
                  case '2':
                    changePage({ page, size, expressStatus: '0' })
                    break;
                  case '3':
                    changePage({ page, size, tradeStatus: '3' })
                    break;
                  case '4':
                    changePage({ page, size, tradeStatus: '5' })
                    break;
                  default:
                    break;
                }
              },
              current: Number(sessionStorage.getItem('currentPage')) || 1,
              pageSize: 10,
              total: totalCount,
              hideOnSinglePage: true,
              showQuickJumper: true
            }}
            renderItem={item => (
              <List.Item key={Math.random()}>
                <List.Item.Meta
                  avatar={<Avatar src={item.url} />}
                  title={<div className="order-title">{`单号：${item['单号']}`}</div>}
                />
                <Descriptions
                  column={2}
                  size="small"
                >
                  {
                    isOrderMessage ?
                      orderConfig.map(config => {
                        return (
                          <Descriptions.Item key={config} label={item[Object.values(config)[0]]} className={Object.values(config)[0] === '商品价格' ? 'price' : ''}>{item[Object.keys(config)[0]]}</Descriptions.Item>
                        )
                      }) :
                      Object.keys(item).map(key => {
                        return ((
                          key !== 'url' &&
                          key !== '单号' &&
                          key !== 'total' &&
                          key !== 'orderId' &&
                          key !== 'orderStatus' &&
                          key !== 'address' &&
                          key !== 'receiveName' &&
                          key !== 'expressStatus' &&
                          key !== 'freight' &&
                          key !== 'className' &&
                          key !== 'addressId' &&
                          key !== 'bookList') ? <Descriptions.Item key={key} label={key} className={key === '商品价格' ? 'price' : ''}>{item[key]}</Descriptions.Item> : '')
                      })
                  }
                </Descriptions>
                <div className="button-box">
                  <Button type="primary" onClick={() => {
                    this.seeOrderMessage(item)
                  }}>
                    查看订单信息
                  </Button>
                </div>
                <div className="order-status" style={{ transform: 'translate(-15px,0)' }}>
                  状态
                  <div
                    className={`status0 ${item.className}`}
                  >
                    {orderStatus[item.orderStatus]}
                  </div>
                </div>
                <div className="order-amount">
                  订单金额
                  <div className="amount">
                    {`¥ ${item.total}`}
                  </div>
                </div>
              </List.Item>
            )}
          />
        }

      </div>
    )
  }
}

export default Order
